package com.moguhoutai.biz;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.moguhoutai.dao.AreaMapper;
import com.moguhoutai.dao.HouseMapper;
import com.moguhoutai.dao.LandlordMapper;
import com.moguhoutai.dao.ModeMapper;
import com.moguhoutai.dao.PayMapper;
import com.moguhoutai.dao.ResourceMapper;
import com.moguhoutai.dao.SubwayMapper;
import com.moguhoutai.dao.TypeMapper;
import com.moguhoutai.model.House;
import com.moguhoutai.util.BusinessException;
import com.moguhoutai.util.Constants;

@Service
public class HouseBiz {
	@Resource
	private AreaMapper aMapperdao;
	@Resource
	private LandlordMapper laMapperdao;
	@Resource
	private ModeMapper mapperdao;
	@Resource
	private PayMapper payMapperdao;
	@Resource
	private ResourceMapper reMapperdao;
	@Resource
	private SubwayMapper subwayMapperdao;
	@Resource
	private TypeMapper typeMapperdao;
	@Resource
	private HouseMapper houseMapperdao;

	public List<House> findAll() throws BusinessException {
		try {
			return houseMapperdao.findAll();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B04");
		}
	}

	public long findCount() throws BusinessException {
		try {
			return houseMapperdao.findCount();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B06");
		}
	}

	public House findById(int houseId) throws BusinessException {
		try {
			return houseMapperdao.selectByPrimaryKey(houseId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B05");
		}
	}

	public void delete(House house) throws BusinessException {
		try {
			houseMapperdao.deleteByPrimaryKey(house.getHouseId());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B02");
		}
	}

	public void save(House house) throws BusinessException {
		try {
			Date now = new Date();
			house.getLanlord().setCreateTime(now);
			house.setCreateTime(now);
			house.setUpdateTime(now);
			house.getRes().setCreateTime(now);
			house.getRes().setUpdateTime(now);
			aMapperdao.insert(house.getArea());
			laMapperdao.insert(house.getLanlord());
			mapperdao.insert(house.getMode());
			payMapperdao.insert(house.getPay());
			reMapperdao.insert(house.getRes());
			subwayMapperdao.insert(house.getSubway());
			typeMapperdao.insert(house.getType());
			houseMapperdao.insert(house);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B01");
		}
	}

	public void update(House house) throws BusinessException {
		try {
			Date now = new Date();
			if (house.getRes() == null) {
				house.getRes().setCreateTime(now);
				house.getRes().setUpdateTime(now);
				reMapperdao.insert(house.getRes());
			}
			house.setCreateTime(now);
			house.setUpdateTime(now);
			houseMapperdao.updateByPrimaryKeySelective(house);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E01B03");
		}
	}

}
